package xuhaijia.lanou3g.autohome.findcar.screen;
//                .-~~~~~~~~~-._       _.-~~~~~~~~~-.
//            __.'              ~.   .~              `.__
//          .'//                  \./                   \\`.
//        .'//            为什么坚持  想一想当初             \\`.
//      .'// .-~"""""""~~~~-._     |     _,-~~~~"""""""~-.  \\`.
//    .'//.-"                 `-.  |  .-'                 "-. \\`.
//  .'//______.============-..   \ | /   ..-============._______\\`.
//.'//____________________________\|/_____________________________\\`.
// 
//                             

import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.sharesdk.framework.ShareSDK;
import xuhaijia.lanou3g.autohome.R;
import xuhaijia.lanou3g.autohome.base.BaseActivity;
import xuhaijia.lanou3g.autohome.base.NetTool;
import xuhaijia.lanou3g.autohome.db.DBToolForCollection;
import xuhaijia.lanou3g.autohome.myself.AutoHomeUser;
import xuhaijia.lanou3g.autohome.myself.Collection;
import xuhaijia.lanou3g.autohome.myself.LoginActivity;
import xuhaijia.lanou3g.autohome.recommend.originalvideo.VideoPlayerActivity;
import xuhaijia.lanou3g.autohome.share.onekeyshare.OnekeyShare;

/**
 * Created by 7 on 16/8/31.
 */
public class ScreenInActivity extends BaseActivity implements View.OnClickListener {

    private TextView title;
    private ImageView iv;
    private TextView type;
    private TextView name;
    private RecyclerView rv;
    private TextView price;
    private ImageView collectionIv;
    private ImageView share;
    private ScreenInAdapter screenInAdapter;
    private TextView carStore;
    private String url;
    ScreenInBean screenInBean;
    private BmobUser bmobUser;
    private Collection collection;


    public ScreenInBean getScreenInBean() {
        return screenInBean;
    }

    public void setScreenInBean(ScreenInBean screenInBean) {
        this.screenInBean = screenInBean;
    }

    @Override
    protected int setLayout() {
        return R.layout.activity_screenin;
    }

    @Override
    protected void initView() {
        title = bindView(R.id.activity_screenin_title);
        iv = bindView(R.id.activity_screenin_iv);
        type = bindView(R.id.activity_screenin_type);
        name = bindView(R.id.activity_screenin_name);
        rv = bindView(R.id.activity_screenin_rv);
        price = bindView(R.id.activity_screenin_price);
        collectionIv = bindView(R.id.activity_screenin_collection);
        share = bindView(R.id.activity_screenin_share);
        share.setOnClickListener(this);
        collectionIv.setOnClickListener(this);
        carStore = bindView(R.id.activity_screenin_carstore);

    }

    @Override
    protected void initData() {
        bmobUser = BmobUser.getCurrentUser();
        Intent intent = getIntent();
        url = intent.getStringExtra("url");

        // 通过两个条件查找
        DBToolForCollection.getInstance().queryIsExistTwo("url = ?", url, "account = ? ", bmobUser.getUsername(), new DBToolForCollection.QueryListener() {
            @Override
            public void onQueryComplete(ArrayList<Collection> mCollections) {

                if (mCollections.size() == 0) {
                    getDataFromNet();
                    collectionIv.setImageResource(R.mipmap.collection);
                } else {
                    collectionIv.setImageResource(R.mipmap.collection_red);
                    title.setText(mCollections.get(0).getTitle());
                    name.setText(mCollections.get(0).getName());
                    mNetTool.getImage(mCollections.get(0).getPicUrl(), iv);
                    price.setText(mCollections.get(0).getPrice());
                    type.setText(mCollections.get(0).getType());
                    carStore.setVisibility(View.GONE);
                    getDataFromNet();

                }
            }
        });
        // 遍历
//        DBToolForCollection.getInstance().queryIsExist("url = ?", url, new DBToolForCollection.QueryListener() {
//            @Override
//            public void onQueryComplete(ArrayList<Collection> mCollections) {
//                if (mCollections.size() == 0) {
//                    getDataFromNet();
//                    collection.setImageResource(R.mipmap.collection);
//                } else {
//                    for (int i = 0; i < mCollections.size(); i++) {
//                        if (mCollections.get(i).getAccount().equals(bmobUser.getUsername())) {
//                            collection.setImageResource(R.mipmap.collection_red);
//                            title.setText(mCollections.get(i).getTitle());
//                            name.setText(mCollections.get(i).getName());
//                            mNetTool.getImage(mCollections.get(i).getPicUrl(), iv);
//                            price.setText(mCollections.get(i).getPrice());
//                            type.setText(mCollections.get(i).getType());
//                            carStore.setVisibility(View.GONE);
//                            getDataFromNet();
//                        }
//                    }
//                }
//            }
//        });

    }

    private void getDataFromNet() {
        GridLayoutManager manager = new GridLayoutManager(this, 2);
        rv.setLayoutManager(manager);
        screenInAdapter = new ScreenInAdapter(this);
        mNetTool.getNetData(url, ScreenInBean.class, new NetTool.NetListener<ScreenInBean>() {
            @Override
            public void onSuccess(final ScreenInBean screenInBean) {
                setScreenInBean(screenInBean);
                title.setText(screenInBean.getResult().getBrandname());
                mNetTool.getImage(screenInBean.getResult().getLogo(), iv);
                type.setText(screenInBean.getResult().getParamlist().get(0).getValue() + "/"
                        + screenInBean.getResult().getParamlist().get(1).getValue());
                name.setText(screenInBean.getResult().getName());
                price.setText(screenInBean.getResult().getFctprice());
                if (screenInBean.getResult().getCarmalltitle().equals("")) {
                    carStore.setVisibility(View.GONE);
                } else {
                    carStore.setText(screenInBean.getResult().getCarmalltitle());
                }
                carStore.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(ScreenInActivity.this, VideoPlayerActivity.class);
                        intent.putExtra("url", screenInBean.getResult().getCarmallurl());
                        startActivity(intent);
                    }
                });
                screenInAdapter.setScreenInBean(screenInBean);
                rv.setAdapter(screenInAdapter);
            }

            @Override
            public void onError(String errorMsg) {

            }
        });
    }

    private void showShare() {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle(getString(R.string.share));
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我是分享文本");
        //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
        oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
//        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");

        // 启动分享GUI
        oks.show(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_screenin_collection:
                if (bmobUser != null) {
                    DBToolForCollection.getInstance().queryIsExistTwo("url = ?", url, "account = ?" ,bmobUser.getUsername() , new DBToolForCollection.QueryListener() {
                        @Override
                        public void onQueryComplete(ArrayList<Collection> mCollections) {
                            if (mCollections.size() == 0) {
                                collectionIv.setImageResource(R.mipmap.collection_red);
                                collection = new Collection();
                                collection.setAccount(bmobUser.getUsername());
                                collection.setLookTime(System.currentTimeMillis());
                                collection.setName(getScreenInBean().getResult().getName());
                                collection.setType(getScreenInBean().getResult().getParamlist().get(0).getValue());
                                collection.setPrice(getScreenInBean().getResult().getFctprice());
                                collection.setPicUrl(getScreenInBean().getResult().getLogo());
                                collection.setUrl(url);
                                collection.setTitle(getScreenInBean().getResult().getBrandname());
                                DBToolForCollection.getInstance().insertCollection(collection);

                                collection.save(new SaveListener<String>() {
                                    @Override
                                    public void done(String s, BmobException e) {
                                        if (e == null) {
                                            Toast.makeText(ScreenInActivity.this, "存入云端成功", Toast.LENGTH_SHORT).show();
                                        } else {
                                            Toast.makeText(ScreenInActivity.this, "存入云端失败请检查网络", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });

                            } else {
                                collectionIv.setImageResource(R.mipmap.collection);
                                DBToolForCollection.getInstance().deleteCollectionByTwoConditions("url = ?" ,url , "account" , bmobUser.getUsername());
                                BmobQuery<Collection> query = new BmobQuery<Collection>();
                                query.addWhereEqualTo("account", bmobUser.getUsername());
                                query.setLimit(10);
                                query.findObjects(new FindListener<Collection>() {
                                    @Override
                                    public void done(List<Collection> list, BmobException e) {
                                        for (int i = 0; i <list.size() ; i++) {
                                            if (list.get(i).getUrl().equals(url)) {
                                                Collection collectionDel = new Collection();
                                                collectionDel.setObjectId(list.get(i).getObjectId());
                                                collectionDel.delete(new UpdateListener() {
                                                    @Override
                                                    public void done(BmobException e) {
                                                        if (e == null) {
                                                            Toast.makeText(ScreenInActivity.this, "删除云端数据成功", Toast.LENGTH_SHORT).show();
                                                        } else {
                                                            Toast.makeText(ScreenInActivity.this, "删除云端数据失败", Toast.LENGTH_SHORT).show();
                                                        }
                                                    }
                                                });
                                            }
                                        }


                                    }
                                });



                            }
                        }
                    });
                } else {
                    Intent intent = new Intent(ScreenInActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.activity_screenin_share:
                showShare();
                break;

        }
    }
}
